<script setup lang="ts">
import { ArrowRight } from '@element-plus/icons-vue'
import { storeToRefs } from 'pinia';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useGlobalStore } from '~/store/global';
import { useSourceStore } from '~/store/source';
import { getTitleTable } from '~/utils/crawler';
import { TitleTableType } from './title-table.vue';

const router = useRouter()

const tableData = ref<TitleTableType[]>([
	{
		title: '二次元',
		url: 'http://ppnn77.xyz/kd/list/12'
	}
])
const { currentUrl } = storeToRefs(useGlobalStore())
const sourcesStore = useSourceStore()
const { sources, currentSourceIdx } = storeToRefs(sourcesStore)

if (sourcesStore.isSourcesEmpty()) {
	sourcesStore.refreshSources().then(() => {
		const source = sources.value[currentSourceIdx.value]
		getTitleTable(currentUrl.value, source.title_table_selectors.category_url, source.title_table_selectors.category_text).then(res => {
			if (!!res) {
				tableData.value = res.map(it => it as TitleTableType)
			} else {
				console.error('response is empty')
			}
		})
	})
} else {
	const source = sources.value[currentSourceIdx.value]
	getTitleTable(currentUrl.value, source.title_table_selectors.category_url, source.title_table_selectors.category_text).then(res => {
		if (!!res) {
			tableData.value = res.map(it => it as TitleTableType)
		} else {
			console.error('response is empty')
		}
	})
}

function goToTitleTable(url: string) {
	currentUrl.value = url
	router.push('/title-table')
}

</script>

<template>
	<div>
		<div mb-5>
			<el-breadcrumb :separator-icon="ArrowRight">
				<el-breadcrumb-item><span font-bold text-black >浏览</span></el-breadcrumb-item>
				<el-breadcrumb-item :to="{ path: '/' }">分类列表</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div>
			<ElCard>
				<el-table :data="tableData" style="width: 100%">
					<el-table-column prop="title" label="网站名">
						<template #default="scope">
							<span @click="() => goToTitleTable(scope.row.url)">{{ scope.row.title }}</span>
						</template>
					</el-table-column>
				</el-table>
			</ElCard>
		</div>
	</div>
</template>